import React, { useState, useEffect } from 'react'
import AuthModal from './AuthModal'
import { Dropdown, Menu } from 'antd'
import { hasLogin, logout } from '~/utils/cookie'
import { getUserInfo } from '~/utils/crypto'
import { useNavigate } from 'react-router-dom'
import { DEFAULT_AVATAR } from '~/const/index'
const UserInfo: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isLogin, setIsLogin] = useState(true)

  const [userInfo, setUserInfo] = useState<any>(null)
  useEffect(() => {
    const userInfo = getUserInfo() || {}
    if (userInfo && Object.keys(userInfo)?.length > 0) {
      setUserInfo(userInfo)
    }
  }, [])
  const navigate = useNavigate()
  const menu = (
    <Menu>
      <Menu.Item key="profile">
        <span onClick={() => navigate('/profile')}>个人资料</span>
      </Menu.Item>
      <Menu.Item key="logout">
        <span
          onClick={() => {
            logout()
          }}
        >
          退出登录
        </span>
      </Menu.Item>
    </Menu>
  )

  const isLoggedIn = hasLogin()
  return (
    <>
      <div className="flex items-center justify-end gap-4 ml-4">
        {isLoggedIn ? (
          <Dropdown overlay={menu} trigger={['click']}>
            <div className="flex items-center gap-3 cursor-pointer">
              <img
                src={userInfo?.avatar || DEFAULT_AVATAR}
                alt="用户头像"
                className="w-8 h-8 rounded-full border border-gray-300"
              />
              <span className="text-gray-700 dark:text-gray-200">
                {userInfo?.nickname || userInfo?.username || '用户'}
              </span>
            </div>
          </Dropdown>
        ) : (
          <div className="flex items-center gap-3">
            <button
              onClick={() => {
                setIsLogin(true)
                setIsModalOpen(true)
              }}
              className="pl-20 pr-2 py-[2px] text-gray-600 dark:text-gray-300 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
            >
              登录
            </button>
            <button
              onClick={() => {
                setIsLogin(false)
                setIsModalOpen(true)
              }}
              className="px-4 py-[2px] bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
            >
              注册
            </button>
          </div>
        )}
      </div>

      <AuthModal
        isOpen={isModalOpen}
        showLogin={isLogin}
        onClose={() => setIsModalOpen(false)}
      />
    </>
  )
}

export default UserInfo
